import https from 'https';

// AtomGit OpenAPI 文档详见 https://docs.atomgit.com/openAPI/api_versioned/remind-page-list
const ATOMGIT_API_BASE_URL = "https://api.atomgit.com";
const MAX_RETRY = 3;

class Service {
  private token: string;
  private messageFailCount = 0;

  constructor(token: string) {
    this.token = token;
  }

  public async getMessages(): Promise<number | undefined> {
    const url = `${ATOMGIT_API_BASE_URL}/notifications/threads?unread=true&page=1`;

    try {
      const response = await this.sendRequest(url, 'GET');
      const data = JSON.parse(response.body);
      const messageCount = data.total || 0;
      this.messageFailCount = 0;
      return messageCount;
    } catch (error) {
      if (error instanceof Error) { // 确保error是一个Error对象
      this.messageFailCount++;
      console.error("request error: ", error.message);
      if (this.messageFailCount === MAX_RETRY) {
        throw new Error("AtomGit 消息 OpenAPI 重复调用失败");
      }
    }
    }
  }

  private sendRequest(path: string, method: 'GET' | 'POST' = 'GET'): Promise<{ statusCode: number, body: string }> {
    return new Promise((resolve, reject) => {
      const options = {
        hostname: 'api.atomgit.com', // 或者你可以从 path 中解析出来
        path: path.replace(ATOMGIT_API_BASE_URL, ''), // 去除基础 URL 部分
        method: method,
        headers: {
          'Accept': 'application/json',
          'Authorization': `Bearer ${this.token}`,
        },
      };

      const req = https.request(options, (res) => {
        let data = '';

        res.on('data', (chunk) => {
          data += chunk;
        });

        res.on('end', () => {
          if (res.statusCode !== 200) {
            reject(new Error(`HTTP error! status: ${res.statusCode}`));
          }
          resolve({ statusCode: 200, body: data });
        });
      });

      req.on('error', (error) => {
        reject(new Error(`Problem with request: ${error.message}`));
      });

      req.end();
    });
  }
}

export { Service };
